import React, { Component } from 'react';
import { withRouter } from 'react-router'

import RaisedButton from 'material-ui/RaisedButton';
import './style.css';
import JudgeTable from '../../components/JudgeTable';

import JudgeLocalStorage from '../../config/JudgeLocalStorage';

// import printJS from 'print.js/src';
import PrintTemplate from 'react-print';
// import htmlPdf from 'html-pdf';
import JsPdf from 'jspdf';
import html2canvas from 'html2canvas';
import TotalScorePopover from '../../components/TotalScorePopover';

import sgdwny from '../../json/sgdw-ny.json';
import sgdwwyty from '../../json/sgdw-wyty.json';
import sgdwglgc from '../../json/sgdw-glgc.json';
import sgdwsygc from '../../json/sgdw-sygc.json';
import jl from '../../json/jl.json';
import jsdw from '../../json/jsdw.json';
const judgeDateMap = {
  '内业考核': { name: "表1 施工单位内业部分考评价表", data: sgdwny, tableType: 'ny' },
  '外业通用': { name: "表2.1 施工外业通用部分考核评价表", data: sgdwwyty, tableType: 'wy' },
  '公路工程': { name: "表2.2 施工外业公路工程考核评价表", data: sgdwglgc, tableType: 'wy' },
  '水路工程': { name: "表2.1 施工外业水路工程考核评价表", data: sgdwsygc, tableType: 'wy' },
  '监理单位考核评价': { name: "表3 监理单位考核评价", data: jl, tableType: 'ny' },
  "建设单位考核评价": { name: "表4 建设单位考核评价", data: jsdw, tableType: 'ny' }
};

class Judge extends Component {
  constructor(props) {
    super(props);

    const { projectId, canMark } = this.props.location.state;

    const projectDate = JudgeLocalStorage.getItem('projects')[projectId];
    console.log("考核标准信息", projectId, projectDate);
    const { judgeClassify } = projectDate;

    const judgeTables = {};

    //根据考核项目设置的考核表类型 获取对应考核表的考试原始数据
    judgeClassify.map(item => {
        console.log(item);
        judgeTables[item] = judgeDateMap[item];
        return null;
      }
    );

    /**
     * 根据考核项目ID获取此次考核的得分数据，如果没有获取到，则构建评分数据数据结构为
     * {"poeject-时间戳':{
     *  '内页考核':{
     *      '责任落实':{
     *          standardScore:10 标准分
     *          isJudge:true,是否参与考核
     *          markScore: 评分
     *          description: 描述
     *          selectMarkStandard:["",""] 选择的扣分标准
     *        }
     *    },
     *    '外业通用':{
     *    }
     * }}
     **/
    const markScoresDB = JudgeLocalStorage.getItem('markScores');
    let markScores = {};
    if (!markScoresDB || !markScoresDB[projectId]) {
      //构建评分数据
      Object.keys(judgeTables).map(key => {
        let judgeTableDate = judgeTables[key].data;

        let judgeClassifyScores = {};

        if (judgeTables[key].tableType === 'ny') {
          judgeTableDate.map((item) => {
            let scoreItem = {};
            scoreItem['standardScore'] = item.standardScore;
            scoreItem['markScore'] = 0;
            scoreItem['description'] = '';
            scoreItem['selectMarkStandard'] = [];
            scoreItem['isJudge'] = true;
            judgeClassifyScores[item.name] = scoreItem;
            return null;
          });
        } else {
          judgeTableDate.map((item) => {
            item.children.map(child => {
              let scoreItem = {};
              scoreItem['standardScore'] = child.standardScore;
              scoreItem['markScore'] = 0;
              scoreItem['description'] = '';
              scoreItem['selectMarkStandard'] = [];
              scoreItem['isJudge'] = true;
              judgeClassifyScores[child.name] = scoreItem;
              return null;
            });
            return null;
          });
        }
        markScores[key] = judgeClassifyScores;
        return null;
      });
    } else {
      markScores = markScoresDB[projectId];
    }

    console.log('评分结果', projectId, markScoresDB);
    this.state = {
      projectDate,
      judgeTables,
      markScores,
      canMark: canMark
    }
  }


  _commitScore = (tableClassify, judgeClassify, newMarkScore) => {
    console.log(tableClassify, judgeClassify, newMarkScore);
    const { markScores } = { ...this.state };
    console.log('老', markScores);
    markScores[tableClassify][judgeClassify] = newMarkScore;
    console.log('新', markScores);
    this.setState({
      markScores: markScores
    });


  };

  /**
   * 保存数据到localStorage
   * @private
   */
  _handleSaveMarkScore = () => {

    const { projectId } = this.props.location.state;
    let markScoresDB = JudgeLocalStorage.getItem('markScores');
    if (markScoresDB) {
      markScoresDB[projectId] = { ...this.state.markScores };
    } else {
      markScoresDB = {};
      markScoresDB[projectId] = { ...this.state.markScores };
    }

    JudgeLocalStorage.setItem('markScores', markScoresDB);

    this.setState({
      canMark: false
    });
    console.log(markScoresDB);
  };
  /**
   * 打印
   * @private
   */
  _savePdf = () => {
    const {history} = this.props;
    const { projectId } = this.props.location.state;
    history.push({
      pathname: '/print', state: {
        projectId: projectId,
        canMark: false
      }
    });
    // html2canvas(document.getElementById("print"), {
    //   onrendered: function (canvas) {
    //     let contentWidth = canvas.width;
    //     let contentHeight = canvas.height;
    //
    //     //一页pdf显示html页面生成的canvas高度;
    //     let pageHeight = contentWidth / 592.28 * 841.89;
    //     //未生成pdf的html页面高度
    //     let leftHeight = contentHeight;
    //     //页面偏移
    //     let position = 0;
    //     //a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
    //     let imgWidth = 595.28;
    //     let imgHeight = 592.28 / contentWidth * contentHeight;
    //
    //     let pageData = canvas.toDataURL('image/jpeg', 1.0);
    //
    //     let pdf = new JsPdf('', 'pt', 'a4');
    //
    //     //有两个高度需要区分，一个是html页面的实际高度，和生成pdf的页面高度(841.89)
    //     //当内容未超过pdf一页显示的范围，无需分页
    //     if (leftHeight < pageHeight) {
    //       pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight);
    //     } else {
    //       while (leftHeight > 0) {
    //         pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight);
    //         leftHeight -= pageHeight;
    //         position -= 841.89;
    //         //避免添加空白页
    //         if (leftHeight > 0) {
    //           pdf.addPage();
    //         }
    //       }
    //     }
    //     pdf.save('content.pdf');
    //
    //   }
    // })

  };

  /**
   * 编辑
   * @private
   */
  _edit = () => {
    this.setState({
      canMark: true
    });
  };



  render() {

    const { judgeTables } = this.state;


    return <div id='judgeDetail' className="judgeContainer">
      <div className="classifyMenu">
        { this.state.canMark ?
          <RaisedButton
            label="保存"
            onClick={this._handleSaveMarkScore}
          /> : null}
        {
          this.state.canMark ? null :
            <RaisedButton
              label="修改"
              onClick={this._edit}
            />
        }
        {
          this.state.canMark ? null : <RaisedButton
            label="打印"
            onClick={this._savePdf}
          /> }
        <TotalScorePopover markScores={this.state.markScores}/>
      </div>
      <div id="print" style={{ backgroundColor: '#fff', padding: '20px' }}>
        {Object.keys(judgeTables).map(key =>
          <JudgeTable key={key}
                      tableClassify={key}
                      tableType={judgeTables[key].tableType}
                      judgeDate={judgeTables[key].data}
                      judgeTableName={judgeTables[key].name}
                      markScores={this.state.markScores[key]}
                      canMark={this.state.canMark}
                      commitScore={this._commitScore}/>
        )}
      </div>
      {/*<PrintTemplate>*/}
      {/*<div id="print">*/}
      {/*{Object.keys(judgeTables).map(key =>*/}
      {/*<JudgeTable key={key}*/}
      {/*tableClassify={key}*/}
      {/*tableType={judgeTables[key].tableType}*/}
      {/*judgeDate={judgeTables[key].data}*/}
      {/*judgeTableName={judgeTables[key].name}*/}
      {/*markScores={this.state.markScores[key]}*/}
      {/*canMark={false}*/}
      {/*commitScore={this._commitScore}/>*/}
      {/*)}*/}
      {/*</div>*/}
      {/*</PrintTemplate>*/}

    </div>
  }
}

export default withRouter(Judge);